package org.jpass.dc.view.project;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.json.annotations.JSON;
import org.jpass.dc.business.project.bean.CFile;
import org.jpass.dc.business.project.bean.CProject;
import org.jpass.dc.business.project.logic.FileService;
import org.jpass.dc.business.project.logic.ProjectService;
import org.jpass.dc.business.user.bean.UserVOBean;
import org.jpass.dc.common.exception.ApplicationException;
import org.jpass.dc.common.util.Constants;
import org.jpass.dc.common.util.ReturnText;
import org.jpass.dc.common.util.StringUtil;
import org.jpass.dc.view.common.BasicAction;

import com.opensymphony.xwork2.Action;

public class FileAction extends BasicAction {
	
	private static final long serialVersionUID = -2489466982145020309L;
	
	private Log log = LogFactory.getLog(FileAction.class);
	
	private FileService fileService = new FileService();
	private ProjectService projectService = new ProjectService();
	
	private CFile cfile = new CFile();
	
	private ReturnText returnText = new ReturnText();
	
	
	private String text;
	
	private Integer depth;
	
	@JSON(serialize = false)
	public CFile getCfile() {
		return cfile;
	}

	public void setCfile(CFile cfile) {
		this.cfile = cfile;
	}
	
	public ReturnText getReturnText() {
		return returnText;
	}

	public void setReturnText(ReturnText returnText) {
		this.returnText = returnText;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	@JSON(serialize = false)
	public Integer getDepth() {
		return depth;
	}

	public void setDepth(Integer depth) {
		this.depth = depth;
	}

	public String create() {
		String message = validateFileInfo();
		if (message != null) {
			returnText.setMsg(message);
			returnText.setType("WARNG");
			returnText.setSuccess(false);
		} else {
			UserVOBean user = this.getCurrentUser();
			String fileParentPath = cfile.getParentPath().substring(0, cfile.getParentPath().length() - 1);
			String projectName = cfile.getParentPath().split("/", 2)[0];
			/*if (!filePath.startsWith("/")) {
				projectName = cfile.getFilePath().split("/", 2)[0];
				filePath = "/" + filePath;
			} 
			if (filePath.endsWith("/")) {
				filePath = filePath.substring(0, filePath.length() - 1);
			}*/
			
			if (projectService.findByUserIdAndProjectName(user.getId(), projectName) == null) { // 判断项目是否存在
				returnText.setMsg("The project \"" + projectName + "\" dose not exist.");
				returnText.setType("WARNG");
				returnText.setSuccess(false);
			} else {
				String resParentPath = new StringBuffer()
						.append(this.getUserRealWrokRootPath())
						.append("/")
						.append(fileParentPath).toString();
				if ("folder".equals(cfile.getFileType())) { // 创建文件夹
					try {
						boolean bool = fileService.createFolder(resParentPath, cfile.getFileName());
						if (!bool) {
							returnText.setMsg("Fail to create a folder \"" + cfile.getFileName() + "\".");
							returnText.setType("ERROR");
							returnText.setSuccess(false);
						}
					} catch (ApplicationException ae) {
						returnText.setMsg(ae.getMessage());
						returnText.setType("ERROR");
						returnText.setSuccess(false);
					} catch (Exception e) {
						returnText.setMsg("Fail to create the folder \"" + cfile.getFileName() + "\".");
						returnText.setType("ERROR");
						returnText.setSuccess(false);
						log.error(user.getEmail() + "创建文件夹时发生异常，异常信息：\n", e);
					}
				} else { // 创建文件
					try {
						boolean bool = fileService.createFile(resParentPath, cfile.getFileName());
						if (!bool) {
							returnText.setMsg("Fail to create this file \"" + cfile.getFileName() + "\".");
							returnText.setType("ERROR");
							returnText.setSuccess(false);
						}
					} catch (ApplicationException ae) {
						returnText.setMsg(ae.getMessage());
						returnText.setType("ERROR");
						returnText.setSuccess(false);
					} catch (Exception e) {
						returnText.setMsg("Fail to create a file.");
						returnText.setType("ERROR");
						returnText.setSuccess(false);
						log.error(user.getEmail() + "创建文件时发生异常，异常信息：", e);
					}
				}
			}
		}
		return Action.SUCCESS;
	}
	
	public String save() {
		if (!StringUtil.isBlank(cfile.getFileName()) && !StringUtil.isBlank(cfile.getParentPath())) {
			UserVOBean user = this.getCurrentUser();
			String filePath = new StringBuffer()
			.append(this.getUserRealWrokRootPath())
			.append("/")
			.append(cfile.getParentPath())
			.append("/")
			.append(cfile.getFileName()).toString();
			try {
				fileService.write(filePath, cfile.getText());
			} catch (IOException e) {
				returnText.setMsg("Fail to save the file \"" + cfile.getFileName() + "\".");
				returnText.setType("ERROR");
				returnText.setSuccess(false);
				log.error(user.getEmail() + "保存文件时发生异常，异常信息：", e);
			}
		} else {
			returnText.setMsg("The file is not exist!");
			returnText.setType("Error");
			returnText.setSuccess(false);
		}
		return Action.SUCCESS;
	}
	
	public String open() {
		if (StringUtil.isBlank(cfile.getFileName()) || StringUtil.isBlank(cfile.getFilePath())) {
			returnText.setMsg("The file \"" + cfile.getFileName() + "\" is not exist.");
			returnText.setType("ERROR");
			returnText.setSuccess(false);
		} else {
			Pattern p = Pattern.compile(Constants.FILTER_FILE_TYPE); 
	        Matcher m = p.matcher(cfile.getFileType());       // 获得匹配器对象
	        if (!m.find()) {
	        	UserVOBean user = this.getCurrentUser();
				StringBuffer pathBuff = new StringBuffer()
				.append(this.getUserRealWrokRootPath())
				.append("/")
				.append(cfile.getFilePath());
				try {
					text = fileService.readFile(pathBuff.toString());
					if (text == null) {
						returnText.setMsg("\"" + cfile.getFileName() + "\" is not file.");
						returnText.setType("ERROR");
						returnText.setSuccess(false);
					}
					
				} catch (IOException e) {
					returnText.setMsg("Exception occurs when open the file \"" + cfile.getFileName() + "\"");
					returnText.setType("ERROR");
					returnText.setSuccess(false);
					log.error(user.getEmail() + "打开" + cfile.getFileName() + "文件时发生异常，异常信息：", e);
				}
	        }
		}
		
		return Action.SUCCESS;
	}
	
	public String delete() {
		if (StringUtil.isBlank(cfile.getFileName()) || StringUtil.isBlank(cfile.getFilePath())) {
			returnText.setMsg("The file \"" + cfile.getFileName() + "\" is not exist!.");
			returnText.setType("ERROR");
			returnText.setSuccess(false);
		} else {
			UserVOBean user = this.getCurrentUser();
			StringBuffer pathBuff = new StringBuffer()
			.append(this.getUserRealWrokRootPath())
			.append("/")
			.append(cfile.getFilePath());
			try {
				if (depth == 1) {
					CProject cp = projectService.findByUserIdAndProjectName(this.getCurrentUser().getId(), cfile.getFileName());
					if (cp == null) {
						returnText.setMsg("The file \"" + cfile.getFileName() + "\" is not exist.");
						returnText.setType("ERROR");
						returnText.setSuccess(false);
					} else {
						try {
							projectService.deleteProject(cp);
							fileService.delete(pathBuff.toString());
						} catch (Exception e) {
							e.printStackTrace();
							returnText.setMsg("Exception occurs when delete the file \"" + cfile.getFileName() + "\"");
							returnText.setType("ERROR");
							returnText.setSuccess(false);
							log.error(user.getEmail() + "删除" + cfile.getFileName() + "文件时发生异常，异常信息：", e);
						}
					}
				} else {
					fileService.delete(pathBuff.toString());
				}
			} catch(FileNotFoundException fe) {
				returnText.setMsg("The file \"" + cfile.getFileName() + "\" is not exist.");
				returnText.setType("ERROR");
				returnText.setSuccess(false);
			} catch (IOException e) {
				returnText.setMsg("Exception occurs when delete the file \"" + cfile.getFileName() + "\"");
				returnText.setType("ERROR");
				returnText.setSuccess(false);
				log.error(user.getEmail() + "删除" + cfile.getFileName() + "文件时发生异常，异常信息：", e);
			}
		}
		return Action.SUCCESS;
	}
	
	
	
	/**
	 * 验证客户端传过来的数据
	 * @return
	 */
	protected String validateFileInfo() {
		/*if (cfile.getFilePath().matches("^[^\\/].*\\/$")) {
			return "The parent folder String is Illegal.";
		}*/
		if (StringUtil.isBlank(cfile.getFileName())) {
			return "The name cannot be empty.";
		}else if (StringUtil.getByteLength(cfile.getFileName().trim()) > 255) {
			return "The length of the name cannot be more than 255.";
		}
		if (StringUtil.isBlank(cfile.getParentPath())) {
			return "The path cannot be empty.";
		}
		
		return null;
	}

}
